var express = require('express');

var router = express.Router();

const userModel = require('../lib/mysql.js');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});
router.post('/login', async function (req, res) {
  var kami = req.body.kami
  var timestamp = req.body.timestamp
  var token = req.body.token
  // console.log(kami + timestamp + token)
  if (kami == undefined || kami == '' || timestamp == undefined || timestamp == '' || token == undefined || token == '') {
    res.send('false')
  } else {
    if (token == 'mbb123456') {
      var items = await userModel.findByKami(kami);
      if (items.length > 0) {
        var item = items[0];
        //卡密正确
        //如果没有激活，激活它
        if (item.active_time == null) {
          var out_time=new Date(new Date().getTime()+item.validity*24*60*60*1000)
          var result= await userModel.activeKami(item.id,out_time)
          res.send('success,'+out_time)
        } else {
          //判断是否有效期
          if ((new Date().getTime()-new Date(item.out_time).getTime())>0) {
            //已经过期
            res.send('errorcode:3')
          } else {
            res.send('success,'+item.out_time)
          }
        }
      } else {
        //无此卡号
        res.send('errorcode:2')
      }
    } else {
      //token不对
      res.send('errorcode:1')
    }
  }
});
router.post('/b/login', async function (req, res) {
  var name = req.body.inputEmail
  var pwd = req.body.inputPassword
  if (name && pwd) {
    var users = await userModel.findUserData(name);
    if (users.length > 0) {
      var user = users[0];
      if (user.password == pwd) {
        var lists = await userModel.findAllKami();
        res.render('list', { name: name, lists: lists });
      } else {
        res.render('message', { message: "密码错误" });
      }
    } else {
      res.render('message', { message: "用户不存在" });
    }
  } else {
    res.render('message', { message: "请输入正确的用户名和密码！" });
  }

});

module.exports = router;
